package com.example.demo.controller;

import com.example.demo.pojo.Account;
import com.example.demo.pojo.Staff;
import com.example.demo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/accs")
    public String list(Model model){
        model.addAttribute("accs", accountService.getAllAccounts());
        return "account/acc_list";
    }

    @GetMapping("/addAccount")
    public String toAddAccount(){ return "account/add"; }

    @PostMapping("/acc")
    public String addAccount(Account account){
        accountService.addNewAccount(account);
        return "redirect:/accs";
    }

    @GetMapping("/account/{id}")
    public String toUpdateAcc(@PathVariable("id")Integer id,Model model){
        model.addAttribute("acc", accountService.getAccountById(id));
        return "account/update";
    }

    @PostMapping("/updateAcc")
    public String updateAcc(Account account){
        accountService.updateAccount(account);
        return "redirect:/accs";
    }
    @PostMapping("/searchAccount")
    public ModelAndView searchAcc(@RequestParam("conditionText") String conditionText,
                                  @RequestParam("conditionType") String conditionType){
        ModelAndView mv = new ModelAndView("account/acc_list");
        mv.addObject("accs",accountService.getAccountsByConditions(conditionText,conditionType));
        return mv;
    }

    @GetMapping("/updatePwd")
    public String toupdatepwd(){
        return "staff/pwd";
    }

    @PostMapping("/updatepwd")
    public String updatepwd(String pwd_old, String pwd_new, HttpSession session){
        Staff staff = (Staff) session.getAttribute("loginuser");
        Account account = accountService.getAccountById(staff.getS_id()) ;
        //String result = accountService.updatePwd(pwd_new, pwd_old,account.getS_id());
        accountService.updatePwd(pwd_new, pwd_old,account.getS_id());
        //if(result != null){

      //  }
        return "redirect:/updatePwd";
    }

}
